package renguanyu.app.tools.controller;

import java.io.File;
import java.net.URL;
import java.util.ResourceBundle;
import java.util.Set;

import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.TextArea;
import javafx.scene.control.TextField;
import javafx.scene.layout.VBox;
import javafx.stage.FileChooser;
import renguanyu.app.tools.model.WordExtract;

public class WordExtractController implements Initializable {

	@FXML
	VBox wordExtractRoot;
	@FXML
	TextField inputFilePath;
	@FXML
	TextArea wordContent;

	WordExtract wordExtract = new WordExtract();

	@Override
	public void initialize(URL location, ResourceBundle resources) {
		inputFilePath.textProperty().bind(wordExtract.inputFilePathProperty());
		wordContent.textProperty().bind(wordExtract.outputFileContentProperty());

	}

	public void openFileInputDialog() {
		FileChooser dirChiooser = new FileChooser();
		String cwd = System.getProperty("user.dir");
		dirChiooser.getExtensionFilters().addAll(new FileChooser.ExtensionFilter("pdf", "*.pdf"));
		File file = new File(cwd);
		dirChiooser.setInitialDirectory(file);
		File chosenDir = dirChiooser.showOpenDialog(wordExtractRoot.getScene().getWindow());
		if (chosenDir != null) {
			String absolutePath = chosenDir.getAbsolutePath();
			wordExtract.setInputFilePath(absolutePath);
		}
	}

	@FXML
	public void extractPdfWord() {
		new Thread(() -> {
			WordExtract pdf = new WordExtract();
			Set<String> words = pdf.getPdfWords(wordExtract.getInputFilePath());
			String result = "";
			for (String word : words) {
				result += word + "\n";
			}
			result += "size=" + words.size();
			wordExtract.setOutputFileContent(result);
		}).start();
	}

}
